<template>
  <div class="app-container">


    <!-- 黑名单列表 -->
    <div v-if="!isAdding">

      <!-- 搜索和新增按钮 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名进行查询"
            clearable
            @clear="getList"
            @keyup.enter.native="getList">
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-input
            v-model="queryParams.idCard"
            placeholder="请输入身份证号进行查询"
            clearable
            @clear="getList"
            @keyup.enter.native="getList">
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-button
            icon="el-icon-search"
            @click="getList">
            查询
          </el-button>
        </el-col>

        <el-col :span="6" class="add-position">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="showAddForm">
            新增
          </el-button>
        </el-col>
      </el-row>



      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="blackListId" />
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="身份证" align="center" prop="idCard">
          <template slot-scope="scope">
            <span>{{ scope.row.idCard || 'N/A' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              type="success"
              plain
              size="small"
              @click="openUpdateDialog(scope.row)">
              修改信息
            </el-button>

            <el-button
              type="danger"
              plain
              size="small"
              @click="handleDelete(scope.row.blackListId)">
              从黑名单中移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 新增黑名单成员表单 -->
    <div v-else class="app-add-container">
      <el-form ref="blacklistForm" :model="blacklistForm" :rules="rules" label-width="120px" class="form-add-container">
        <h2 class="form-add-title">新增黑名单成员</h2>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="blacklistForm.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="blacklistForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="large">确认拉黑</el-button>
          <el-button @click="onReset" size="large">重置</el-button>
          <el-button @click="cancelAdd" size="large">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 修改信息的弹窗 -->
    <el-dialog
      title="修改信息"
      :visible.sync="updateDialogVisible"
      width="500px">
      <el-form :model="updateForm" ref="updateForm" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="updateForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="updateForm.idCard"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBlacklist, deleteBlacklist, updateBlacklist, addBlackList } from "@/api/Empment/blacklist";
import { MessageBox, Message } from 'element-ui';

export default {
  name: "EpmBlacklist",
  data() {
    return {
      tableData: [],
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: "", // 用于搜索用户名的参数
        idCard: "",   // 用于搜索身份证号的参数
      },
      updateDialogVisible: false,
      updateForm: {
        blackListId: null,
        userName: "",
        idCard: "",
      },
      isAdding: false, // 控制显示列表或添加表单
      blacklistForm: {
        userName: "",
        idCard: "",
      },
      rules: {
        userName: [
          { message: "请输入用户姓名", trigger: "blur" },
        ],
        idCard: [
          { message: "请输入身份证号", trigger: "blur" },
          // 身份证验证
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "身份证号格式不正确", trigger: "blur" }
        ],
      },
    };
  },

  methods: {
    getList() {
      this.fetchData();
    },

    fetchData() {
      this.loading = true;
      getBlacklist(this.queryParams)
        .then(response => {
          this.tableData = response.rows;
          this.loading = false;
          this.total = response.total;
        })
        .catch(error => {
          console.error("加载数据时出现错误:", error);
          this.loading = false;
        });
    },

    handleDelete(blackListId) {
      MessageBox.confirm('确定要将该用户移除黑名单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBlacklist(blackListId)
          .then(() => {
            Message.success('成功将该用户移出黑名单');
            this.fetchData(); // 重新加载数据
          })
          .catch(error => {
            console.error('数据操作时出现错误:', error);
            Message.error('移除失败');
          });
      }).catch(() => {
        Message.info('操作已取消');
      });
    },

    openUpdateDialog(row) {
      this.updateForm = { ...row };
      this.updateDialogVisible = true;
    },

    submitUpdate() {
      updateBlacklist(this.updateForm)
        .then(() => {
          Message.success('信息修改成功');
          this.updateDialogVisible = false;
          this.fetchData(); // 重新加载数据
        })
        .catch(error => {
          console.error('修改时出现错误:', error);
          Message.error('修改失败');
        });
    },

    showAddForm() {
      this.isAdding = true; // 切换到新增表单
    },

    cancelAdd() {
      this.isAdding = false; // 取消新增操作，返回列表
    },

    onSubmit() {
      // 手动校验 userName 和 idCard 是否至少有一个不为空
      if (!this.blacklistForm.userName && !this.blacklistForm.idCard) {
        Message.error('用户名和身份证号不能同时为空');
        return;
      }

      this.$refs.blacklistForm.validate((valid) => {
        if (valid) {
          addBlackList(this.blacklistForm)
            .then(() => {
              Message.success('成功新增黑名单人员');
              this.onReset(); // 提交成功后重置表单
              this.isAdding = false; // 提交成功后返回列表
              this.fetchData(); // 刷新列表数据
            })
            .catch(error => {
              console.error("添加黑名单时出现错误:", error);
              Message.error('添加失败');
            });
        } else {
          Message.error('表单填写有误');
          return false;
        }
      });
    },

    onReset() {
      this.$refs.blacklistForm.resetFields();
    }
  },

  mounted() {
    this.fetchData(); // 组件挂载后加载数据
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.form-container {
  width: 600px;
  padding: 45px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px 0 rgba(0,0,0,.1);
}

.form-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}


.app-add-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  background: #f0f2f5;
}

.form-add-container {
  width: 600px;
  padding: 45px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px 0 rgba(0,0,0,.1);
}

.form-add-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.add-position {
  position: absolute;
  left: 1200px;
}
</style>
